import json
import os
import subprocess
from fastapi import APIRouter, UploadFile, Depends
from sqlalchemy.orm import Session
import pkg_resources
from models.system import System
from schemas import response_success, response_error
from schemas.system import ConfigSchema, InstallPackageSchema
from models.db import get_db
import pip
system_router = APIRouter()
router = system_router


@router.post("/load-python")
def load_python(path: str):
    sr = subprocess.run(f'{path} -c "import site; print(site.getsitepackages())"', shell=True, stdout=subprocess.PIPE)
    try:
        package_dir = eval(sr.stdout.decode())
    except SyntaxError:
        return response_error(msg='未获取到数据')
    package_dir = list(filter(lambda x: 'site-packages' in x, package_dir))
    packages = []
    for _dir in package_dir:
        packages.extend(os.listdir(_dir))
    # packages = list(map(lambda x: {'title': x}, packages))
    packages = list(filter(lambda x: not x.startswith('_') and not x.endswith('.dist-info'), packages))
    return response_success(data={'packages': packages})


@router.post("/upload-install")
async def upload_install(python: str, file: UploadFile):
    cache_dir = 'cache/python_packages/'
    if not os.path.isdir(cache_dir):
        os.mkdir(cache_dir)
    package_dir = os.path.join(cache_dir, file.filename.replace('.tar.gz', ''))

    contents = await file.read()
    with open(os.path.join(cache_dir, file.filename), "wb") as f:
        f.write(contents)
    sr = subprocess.run(f"tar -xf {os.path.join(cache_dir, file.filename)} -C {cache_dir}",
                        stdout=subprocess.PIPE, shell=True)
    if sr.returncode != 0:
        return response_error(msg='文件解压失败！')

    sr = subprocess.run(f"{python} -m pip install {package_dir}/*", stdout=subprocess.PIPE, shell=True)
    print(sr.stdout.decode())
    if sr.returncode != 0:
        return response_error(msg='安装失败')

    return response_success(msg='安装成功')

@router.post("/install-online")
async def install_online(form: InstallPackageSchema ):
    status = pip.main(['install', form.package_name])
    if status == 0:
        return response_success(msg='安装成功')
    else:
        return response_error(msg='安装失败')


@router.get("/config")
async def config(db: Session = Depends(get_db)):
    system = db.query(System).first()
    system_config = json.loads(system.config)

    interpreter = {"path": "./venv/bin/python", "packages": []}
    if not system_config.get('interpreter'):
        system_config['interpreter'] = interpreter

    packages = []

    installed_packages = pkg_resources.working_set
    for package in installed_packages:
        # f"{package.project_name}=={package.version}"
        packages.append({
            'name': package.project_name,
            'version': package.version
        })
    system_config["interpreter"]['packages'] = packages

    return response_success(data={'config': system_config})


@router.post("/config")
async def config(form: ConfigSchema, db: Session = Depends(get_db)):
    system = db.query(System).first()
    if system:
        system.config = json.dumps(form.config)
    else:
        db.add(System(config=json.dumps(form.config)))
    db.commit()
    return response_success("更新成功", data=system)
